import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:zhibao_flutter/util/check/check.dart';
import 'package:zhibao_flutter/util/float/fram_size.dart';
import 'package:zhibao_flutter/util/func/log.dart';
import 'package:zhibao_flutter/util/my_theme.dart';
import 'package:get/get.dart';

Future<String?> selectDateThemeBirthdayDialog(
  context, {
  final DateTime? initDate,
  final bool isAfter = false,

  /// Only When [isAfter] is true be works.
  final bool isContainToday = true,

  /// Least eighteen[18] years old.
  final bool leastEighteen = true,
}) {
  return showModalBottomSheet(
    context: context,
    backgroundColor: Colors.transparent,
    builder: (context) {
      return Material(
        type: MaterialType.transparency,
        child: SelectDateThemeBirthdayDialog(
            initDate, isAfter, isContainToday, leastEighteen),
      );
    },
  );
}

class SelectDateThemeBirthdayDialog extends StatefulWidget {
  final DateTime? initDate;
  final bool isAfter;
  final bool isContainToday;
  final bool leastEighteen;

  const SelectDateThemeBirthdayDialog(
      this.initDate, this.isAfter, this.isContainToday, this.leastEighteen,
      {Key? key})
      : super(key: key);

  @override
  _SelectDateThemeBirthdayDialogState createState() =>
      _SelectDateThemeBirthdayDialogState();
}

class _SelectDateThemeBirthdayDialogState
    extends State<SelectDateThemeBirthdayDialog> {
  FixedExtentScrollController controller = FixedExtentScrollController();
  FixedExtentScrollController yearController = FixedExtentScrollController();
  FixedExtentScrollController monthController = FixedExtentScrollController();

  int currentYear = DateTime.now().year;
  int currentMouth = DateTime.now().month;
  int currentDay = DateTime.now().day;

  List<int> years = List.generate(30, (index) {
    return DateTime.now().year + index;
  });
  List<int>? mouths;

  List<int>? days;

  @override
  void initState() {
    super.initState();
    years = List.generate(30, (index) {
      if (widget.isAfter) {
        return DateTime.now().year + index;
      } else {
        return DateTime.now().year - index - (widget.leastEighteen ? 18 : 0);
      }
    });
    setMonthAsFull();
    setDaysAsFull();
    initDate();
  }

  void setDaysAsFull() {
    days = List.generate(
        MyDate.getDays(currentYear)[currentMouth - 1], (index) => index + 1);
  }

  void setMonthAsFull() {
    mouths = List.generate(12, (index) {
      return DateTime(currentYear).month + index;
    });
  }

  Future initDate() async {
    if (widget.initDate != null) {
      currentYear = widget.initDate!.year;
      currentMouth = widget.initDate!.month;
      currentDay = widget.initDate!.day;
    } else if (widget.leastEighteen) {
      currentYear = years.first;
      currentMouth = mouths!.first;
      currentDay = days!.first;
    } else {
      final now = DateTime.now();
      currentYear = now.year;
      currentMouth = now.month;
      currentDay = now.day;
    }

    await handleMonths();
    await handleDays();
    setState(() {});

    await yearController.animateToItem(years.indexOf(currentYear),
        duration: Duration(milliseconds: 50), curve: Curves.bounceIn);
    await monthController.animateToItem(mouths!.indexOf(currentMouth),
        duration: Duration(milliseconds: 50), curve: Curves.bounceIn);
    await controller.animateToItem(days!.indexOf(currentDay),
        duration: Duration(milliseconds: 50), curve: Curves.bounceIn);
  }

  Future handleDays() async {
    /// When current month and year is nearest refresh the [days] to don't
    /// show passed day.
    final nowYear = DateTime.now().year;
    final nowMonth = DateTime.now().month;
    final nowDay = DateTime.now().day;

    int dayNumValueOfFull = MyDate.getDays(currentYear)[currentMouth - 1];
    final dayLength = dayNumValueOfFull - nowDay;

    final todayShow = widget.isContainToday ? 1 : 0;

    /// Only [widget.isAfter] is true handle.
    if (!widget.isAfter) {
      if (currentYear == nowYear && currentMouth == nowMonth) {
        days = List.generate(
            nowDay - (widget.isContainToday ? 0 : 1), (index) => index + 1);
      } else {
        setDaysAsFull();
      }
      return;
    }

    if (currentYear != nowYear || currentMouth != nowMonth) {
      setDaysAsFull();
      return;
    }

    days = List.generate(
        dayLength + todayShow, (index) => index + nowDay + 1 - todayShow);
  }

  Future handleMonths() async {
    final nowYear = DateTime.now().year;

    /// Only [widget.isAfter] is true handle.
    if (!widget.isAfter) {
      LogUtil.d("years.first::${years.first}");
      if (currentYear == nowYear) {
        final nowMonth = DateTime.now().month;
        mouths = List.generate(12 - nowMonth, (index) {
          return index + 1;
        });
      } else {
        setMonthAsFull();
      }
      return;
    }

    /// If Current select year is nearest refresh the [mouths] to don't
    /// show passed month else the [mouths] show normal data.
    if (currentYear != years.first) {
      setMonthAsFull();
      return;
    }

    final nowMonth = DateTime.now().month;
    mouths = List.generate(12 - nowMonth + 1, (index) {
      return DateTime(currentYear).month + index + nowMonth - 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 274.5 + FrameSize.padBotH(),
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: 5),
            decoration: BoxDecoration(border: MyTheme.mainBorder()),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                InkWell(
                  child: Container(
                    width: 60,
                    padding: EdgeInsets.symmetric(vertical: 15),
                    alignment: Alignment.center,
                    child: Text(
                      '取消',
                      style: TextStyle(
                        color: Color(0xff121212),
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                  onTap: () => Get.back(),
                ),
                Text(
                  '请选择生日',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                ),
                InkWell(
                  child: Container(
                    width: 60,
                    padding: EdgeInsets.symmetric(vertical: 15),
                    alignment: Alignment.center,
                    child: Text(
                      '确定',
                      style: TextStyle(
                        color: Color(0xffFF2E18),
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                  onTap: () => Get.back(
                    // result:
                    //     '${DateTime(currentYear, currentMouth, currentDay).millisecondsSinceEpoch ~/ 1000}',
                    result:
                        '$currentYear/${'${doubleNum(currentMouth)}/${doubleNum(currentDay)}'}',
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: Row(
              children: [
                Expanded(
                  child: CupertinoPicker.builder(
                    itemExtent: 45,
                    backgroundColor: Colors.white,
                    selectionOverlay: Container(),
                    childCount: years.length,
                    scrollController: yearController,
                    onSelectedItemChanged: (d) async {
                      currentYear = years[d];
                      await handleMonths();
                      await handleDays();

                      if (controller.offset > 0) controller.jumpTo(0);
                      if (monthController.offset > 0) monthController.jumpTo(0);
                      setState(() {});
                    },
                    itemBuilder: (context, index) {
                      return Container(
                        height: 45,
                        alignment: Alignment.center,
                        child: Text('${years[index]}年'),
                      );
                    },
                  ),
                ),
                Expanded(
                  child: CupertinoPicker.builder(
                    itemExtent: 45,
                    childCount: mouths!.length,
                    scrollController: monthController,
                    backgroundColor: Colors.white,
                    selectionOverlay: Container(),
                    onSelectedItemChanged: (d) async {
                      currentMouth = mouths![d];
                      await handleDays();
                      if (controller.offset > 0) controller.jumpTo(0);
                      setState(() {});
                    },
                    itemBuilder: (context, index) {
                      return Container(
                        height: 45,
                        alignment: Alignment.center,
                        child: Text('${mouths![index]}月'),
                      );
                    },
                  ),
                ),
                Expanded(
                  child: CupertinoPicker.builder(
                    itemExtent: 45,
                    backgroundColor: Colors.white,
                    selectionOverlay: Container(),
                    onSelectedItemChanged: (dIndex) {
                      LogUtil.d("Day::onSelectedItemChanged::$dIndex");
                      currentDay = days![dIndex];
                    },
                    scrollController: controller,
                    childCount: days?.length ?? 0,
                    itemBuilder: (context, index) {
                      final int item = days![index];
                      return Container(
                        height: 45,
                        alignment: Alignment.center,
                        child: Text('$item日'),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
